package com.glsc.ngateway.flowable.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;

public class DateUtil {

    private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);

    public static String formatSecond = "yyyy-MM-dd HH:mm:ss";

    /**
     * 功能描述:
     *
     * @param: 获取当前系统时间 yyyy-MM-dd HH:mm:ss
     * @return:
     * @auther: youqing
     * @date: 2019/10/8 9:58
     */
    public static String getCurrentDate(String formatSecondSimple) {
        SimpleDateFormat df = new SimpleDateFormat(formatSecondSimple);
        String date = df.format(System.currentTimeMillis());
        return date;
    }

    public static String today() {
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return today.format(formatter);
    }

    public static String today(String format) {
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        return today.format(formatter);
    }

    public static String year1970() {
        LocalDate today = LocalDate.ofYearDay(1970, 1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return today.format(formatter);
    }

    public static String firstDayOfYear() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//日期格式化
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
        Date date = new Date();
        //设置默认显示的时间
        Calendar calendar = Calendar.getInstance();
        int year = Integer.parseInt(sdf1.format(date));
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DATE, 1);
        String mrdate = sdf.format(calendar.getTime());//今年元旦
        return mrdate;
    }

    /**
     * @author mengl
     * @date 2020/08/12
     * 根据传入参数 取当年第一天
     */
    public static String firstDayOfYear2(String exchDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//日期格式化
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
        Date day = null;
        try {
            day = sdf.parse(exchDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        int year = Integer.parseInt(sdf1.format(day));
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DATE, 1);
        String mrdate = sdf.format(calendar.getTime());//今年元旦
        return mrdate;
    }

    public static String dtFormatter1(String day) {
        LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern("yyyyMMdd"));
        return date.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
    }


    public static String dtFormatter2(String day) {
        LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern("yyyyMMdd"));
        return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String dtFormatter3(String day) {
        LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern("yyyyMMdd"));
        return date.format(DateTimeFormatter.ofPattern("MM月dd日"));
    }

    public static String dtFormatter4(String day) {
        LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern("yyyyMMdd"));
        return date.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
    }

    //自适应格式，最终将日期转为yyyy-MM-dd by mengl
    public static String dtFormatterAUTO(String day) {
        if (ToolUtils.isNotEmpty(day) && day.contains("-")) {
            return day;
        }
        LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern("yyyyMMdd"));
        return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    //自适应格式，最终将日期转为yyyyMMdd by mengl
    public static String AUTOToYyyyMMDD(String day) {
        String res = day;
        if (ToolUtils.isNotEmpty(day) && day.contains("-")) {
            LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            res = date.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        }
        return res;
    }

    public static String dtFormatter1Today() {
        return LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
    }

    public static String now() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        return now.format(formatter);
    }


    public static String now_hms() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        return now.format(formatter);
    }

    public static boolean validDate(String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        try {
            formatter.parse(date);
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }

    public static boolean validDateFormat(String date, String dateFormat) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
        try {
            formatter.parse(date);
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }

    public static LocalDateTime fromString(String datetime) {
        return fromString(datetime, "yyyy-MM-dd HH:mm:ss");
    }

    public static LocalDateTime fromString(String datetime, String formatter) {
        if (datetime == null) {
            return null;
        }
        try {
            return LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern(formatter));
        } catch (DateTimeParseException e) {
            return null;
        }
    }

    public static String toString(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            return null;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(formatter);
    }

    public static String toYMD(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            return null;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return localDateTime.format(formatter);
    }

    public static void Utf8ToUnicode(String str) throws Exception {
        byte[] bArr = str.getBytes("utf8");  //bArr[0]=fe,bArr[1]=ff;从bArr[2]开始为编码内容
        String str1 = new String(bArr, "gbk");  //utf16和unicode编码一样
        System.out.println(str1);
    }

    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GB2312
                String s = encode;
                return s; //是的话，返回“GB2312“，以下代码同理
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是ISO-8859-1
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是UTF-8
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GBK
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return ""; //如果都不是，说明输入的内容不属于常见的编码格式。
    }


    /**
     * @author mengl
     * @date 2020/08/12
     */
    public static String nowTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
        return now.format(formatter);
    }

    /**
     * @author mengl
     * @date 2020/08/12
     * 前天
     */
    public static String beforreDay() {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -2);
        String beforreDay = dateFormat.format(calendar.getTime());
        return beforreDay;
    }

    /**
     * 按照指定日期，获取当月剩余的日期，包含指定日期
     *
     * @author mengl
     * @date 2020/08/12
     */
    public static List<String> getMonthEveryLastDays(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        List<String> list = new ArrayList<>();
        try {
            Date day = sdf.parse(date);
            Calendar cal = Calendar.getInstance();
            cal.setTime(day);
            int maxday = cal.getActualMaximum(Calendar.DATE);//当月最大天数
            int today = cal.get(Calendar.DAY_OF_MONTH);//日
            list.add(sdf.format(cal.getTime()));
            for (int i = 1; i <= (maxday - today); i++) {
                cal.add(Calendar.DAY_OF_MONTH, 1);
                String aDate = sdf.format(cal.getTime());
                list.add(aDate);
            }
            return list;
        } catch (ParseException e) {
            logger.info("转换为Date错误:" + date);
        }
        return null;
    }

    /**
     * 按照指定日期，获取当月所有的自然日期，包含指定日期
     *
     * @author mengl
     * @date 2020/08/12
     */
    public static List<String> getMonthEveryDays(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        List<String> list = new ArrayList<>();
        try {
            Date day = sdf.parse(date);
            Calendar cal = Calendar.getInstance();
            cal.setTime(day);
            int year = cal.get(Calendar.YEAR);//年
            int month = cal.get(Calendar.MONTH);//月
//            int today = cal.get(Calendar.DAY_OF_MONTH);//日
            int maxday = cal.getActualMaximum(Calendar.DATE);//当月最大天数
            for (int i = 1; i <= maxday; i++) {
                cal.set(year, month, i);
                String aDate = sdf.format(cal.getTime());
                list.add(aDate);
            }
            return list;
        } catch (ParseException e) {
            logger.info("转换为Date错误:" + date);
        }
        return null;
    }

    /**
     * 获取当年的第一天
     *
     * @return
     * @author libj
     */
    public static String getCurrYearFirst() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取某年第一天日期
     *
     * @param year 年份
     * @return Date
     * @author libj
     */
    public static String getYearFirst(int year) {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        String currYearFirst = dateFormat.format(calendar.getTime());
        return currYearFirst;
    }

    /**
     * @author yaoy
     * @date 2020/10/25
     * 计算不同日期天数间隔
     */
    public static Integer getDayRange(String beginDay, String endDay) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date d1 = sdf.parse(beginDay);
        Date d2 = sdf.parse(endDay);
        Long daysBetween = (d2.getTime() - d1.getTime() + 1000000) / (60 * 60 * 24 * 1000);
        return daysBetween.intValue();
    }

    /**
     * @author mengl
     * @date 2020/11/02
     * 获得当前时刻两秒的时刻
     */
    public static String beforeSecond(String time) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        Date date = sdf.parse(time);
        calendar.setTime(date);
        calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) - 2);
        return sdf.format(calendar.getTime());
    }


    /**
     * 获取日期为date的afterDay天后的日期
     *
     * @param date
     * @param afterDay
     * @return
     */
    public static String getAfterDate(String date, Integer afterDay) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            Date day = sdf.parse(date);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(day);
            calendar.add(calendar.DATE, afterDay);
            day = calendar.getTime();
            String mrdate = sdf.format(day);//
            return mrdate;
        } catch (ParseException e) {
            logger.info("转换为Date错误:" + date);
        }
        return null;
    }

    public static String stampToDate(int time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time_Date = sdf.format(new Date(time * 1000L));
        return time_Date;

    }

    public static List<String> getYearMonth(String beginDate, String endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMM");
        List<String> list = new ArrayList<>();
        try {
            Date day = sdf.parse(endDate);
            Calendar endCal = Calendar.getInstance();
            endCal.setTime(day);

            Date beginDay = sdf.parse(beginDate);
            Calendar beginCal = Calendar.getInstance();
            beginCal.setTime(beginDay);


            while (beginCal.before(endCal)) {
                String aDate = sdf2.format(beginCal.getTime());
                list.add(aDate);
                beginCal.add(Calendar.MONTH, 1);
            }

            return list;
        } catch (ParseException e) {
            logger.info("转换为Date错误:" + endDate);
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
//        String s = AUTODate("20201214","20210616");
//        System.out.println(s);
//        System.out.println(beforeSecond("15:00:00"));

//        System.out.println(validDate("19900731"));
//        System.out.println(validDateFormat("1992-07-05","yyyy-MM-dd"));
//        System.out.println(validDateFormat("1992-07-32","yyyy-MM-dd"));
//        System.out.println(firstDayOfYear());

        System.out.println(stampToDate(1621249324));

    }

}
